<template>
  <el-dialog
    v-model="visible"
    :modal="false"
    :title="$t('user.userImport')"
    :close-on-click-modal="false"
    width="38%"
  >
    <span
      v-for="(note, i) in (isEn() ? notesEn : notes)"
      :key="note"
    >{{ note }}<br v-if="i < notes.length - 1"></span>
    <el-button
      style="margin-left: 10px;"
      text
      type="primary"
      @click="onDownloadModel()"
    >
      {{ $t('product.downloadTemplate') }}
    </el-button>
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      :action="http.adornUrl('/admin/user/importExcel')"
      :headers="{Authorization: cookie.get('bbcAuthorization_vp'),locale:lang}"
      :limit="1"
      name="excelFile"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-error="uploadFalse"
      :on-success="uploadSuccess"
      :file-list="files"
      :auto-upload="false"
      :before-upload="beforeAvatarUpload"
    >
      <template #trigger>
        <el-button

          type="success"
        >
          {{ $t('product.selectFile') }}
        </el-button>
      </template>
      <el-button
        style="margin-left: 10px;"

        type="primary"
        @click="onSubmitUpload"
      >
        {{ $t('components.confirmUpload') }}
      </el-button>
    </el-upload>
  </el-dialog>
</template>
<script setup>
import cookie from 'vue-cookies'
import { ElMessage } from 'element-plus'
import http from '@/utils/http'
import { clearLoginInfo } from '@/utils/index.js'
import $t from '@/utils/$t'
import { ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'

const visible = ref(true)

const emit = defineEmits(['refreshDataList'])

const lang = localStorage.getItem('bbcLang') || 'zh_CN'
const files = ref([])
const notes = [
  '注意：',
  '   1、请勿修改表格中的字段顺序，或随意增加、删除表格字段,上传模板大小不能超过 10MB,超过应该分批导入',
  '   2、会员等级根据配置成长值等级自动设置',
  '   3、导入用户期间，请勿修改会员等级设置',
  '   4、根据手机号(必须是11位)作为唯一标识，如果导入的手机号已存在，不会更新用户的任何数据.',
  '   5、国家/地区不同，手机号的验证规则也不同，导入时不会验证手机号码的真实性，请谨慎填写，导入错误数据请自行负责.',
  '   6、如果是付费会员必须填写vip结束时间.'
]
const notesEn = [
  ' Note: ',
  ' 1, Please do not modify the order of the fields in the form, or arbitrarily add or delete form fields, upload the template size can not exceed 10MB, more than should be imported in batches ',
  ' 2、The Member level is set automatically according to the configured growth value level ',
  ' 3、Do not modify the membership level settings during user import ',
  ' 4、According to the cell phone number as a unique identification, if the imported cell phone number already exists, will not update any data of the user.',
  ' 5、The verification rules for cell phone numbers are different for different countries/regions, and the authenticity of cell phone numbers will not be verified when importing, so please fill in the form carefully and be responsible for importing wrong data.',
  ' 6、If it is a paid member must fill in the vip end time'
]
const uploadSuccess = (response) => {
  alert(response.data)
  files.value = []
  visible.value = false
  emit('refreshDataList')
}
const uploadFalse = (response) => {
  alert(isEn() ? 'File upload failed!' : '文件上传失败！')
}
const init = () => {
  visible.value = true
}
let upload = false
// 上传前对文件的大小的判断
const beforeAvatarUpload = (file) => {
  upload = true
  const extension = file.name.split('.')[1] === 'xls'
  const extension2 = file.name.split('.')[1] === 'xlsx'
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!extension && !extension2) {
    alert(isEn() ? 'Upload template can only be in xls, xlsx format!' : '上传模板只能是 xls、xlsx格式!')
  }
  if (!isLt2M) {
    alert(isEn() ? 'Upload template size cannot exceed 10MB' : '上传模板大小不能超过 10MB!')
  }
  return extension || (extension2 && isLt2M)
}
const uploadRef = ref(null)
const onSubmitUpload = () => {
  // if (businessType != null) {
  // 触发组件的action
  uploadRef.value?.submit()
  if (!upload) {
    ElMessage.error($t('order.uploadInvoiceTip'))
  }
}

const handleRemove = () => {
  // console.log(file)
}
// 下载模板
const onDownloadModel = () => {
  http({
    url: http.adornUrl('/admin/user/importUserModel'),
    method: 'get',
    responseType: 'blob' // 解决文件下载乱码问题
  }).then(async ({ data }) => {
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    // 读取文件内容
    try {
      const TEXT = await (new Response(blob)).text()
      const result = JSON.parse(TEXT)
      // console.log(result)
      if (result.code === 'A00004') {
        ElMessage({
          message: result.msg || $t('loginExpired'),
          type: 'error',
          duration: 1500,
          onClose: () => {
            nextTick(() => {
              clearLoginInfo()
              useRouter().replace({ name: 'login' })
            })
          }
        })
        return
      }
    } catch (error) {
    }
    const fileName = isEn() ? 'UserInfoImportTemplate.xlsx' : '导入用户信息模板.xlsx'
    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
}
const handlePreview = (file) => {
  if (file.status) {
    alert(isEn() ? 'This file import success' : '此文件导入成功')
  } else {
    alert(isEn() ? 'This file import failed' : '此文件导入失败')
  }
}

const isEn = () => {
  if ($t('language') === 'language') {
    return true
  } else {
    return false
  }
}

defineExpose({
  init
})
</script>
